package com.geostar.gmp.utils;

import java.io.IOException;
import java.io.StringWriter;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 文件名:JsonUtils.java
 * 功能: 提供json与对象的相互转换的方法，并发提供以json形式响应请求
 * 目前支持方法
 * --------------------------------------
 * 初始版本 
 * 作者: yesong
 * 时间: Apr 8, 2014
 */
public class JsonUtils {

	private static JsonGenerator jsonGenerator;
	private static ObjectMapper objectMapper;
	private static StringWriter writer;
	
	/**
	 * 目的: 初始化json factory
	 */
	public static void create() {
		objectMapper = new ObjectMapper();
		try {
			writer = new StringWriter();  
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(writer);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 目的:销毁json factory
	 */
	 public static void destory() {
		try {
			if (jsonGenerator != null) {
				jsonGenerator.flush();
			}
			if (!jsonGenerator.isClosed()) {
				jsonGenerator.close();
			}
			if (writer != null){
				writer.close();
			}
			jsonGenerator = null;
			objectMapper = null;
			writer = null;
			System.gc();
		} catch (IOException e) {
			e.printStackTrace();
		}
	 }
	 
	 /***
	  * 目的: javabean转为json
	  * @param obj 包括javabean，map，list
	  * @return
	  */
	 public static String bean2Json(Object obj){
		 create();
		 String json = null;
		 try {
			objectMapper.writeValue(jsonGenerator,obj);
			json = writer.toString();
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			destory();
		}
		 return json;
	 }
}
